<?php

namespace App\Http\Controllers\Admin;

use App\Handlers\ImageUploadHandler;
use App\Http\Controllers\ApiController;
use App\Models\Category;
use App\Models\Goods;
use App\Models\GoodsImage;
use App\Models\Product;
use App\Models\Props;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Symfony\Component\Process\Pipes\AbstractPipes;

class SpuController extends Controller
{
    public static $view_path = 'admin.spu.';

    /**商品列表首页
     * @param Request $request
     * @param Goods $goodsModel
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index(Request $request, Goods $goodsModel)
    {
        return view(self::$view_path . 'index', [
                'spuedit_url'=>url('admin/spu/edit'),
                'spuedel_url'=>url('admin/spu/del'),
                'spulist_url'=>url('admin/spu/ajax_spu_list'),
            ]
        );
    }

    /**
     * TemplateController下的ajax goods列表
     */
    public function ajax_spu_list_of_templateController(Request $request,Goods $goods)
    {
        $data = $goods -> admin_api_goods_list($request->all());
        return \Response::json($data);
    }


    public function ajax_spu_list(Request $request, Goods $goodsModel)
    {
        $data = $goodsModel->data($request);
        return \Response::json($data);
    }

    /**商品创建方法
     * @param Request $request
     * @param Goods $goodsModel
     */
    public function docreate(Request $request, Goods $goodsModel)
    {
        if (!$goodsModel->add($request->all())) {
            return ApiController::response(null, ApiController::ERROR_CODE, $goodsModel->error);
        }

        return ApiController::response();
    }

    /**创建商品的页面
     * @param Request $request
     * @param Props $propsModel
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function create_form(Request $request, Props $propsModel, Goods $goodsModel)
    {
        $data['image_list'] = [];
        $data['action'] = 'create';
        $data['pro_val_list'] = $propsModel->getProplist();
        $cate = Category::all()->toArray();
        $data['cat_list'] = $goodsModel->getHtmlCate($cate);
        $data['action'] = 'create';
//        dd($data);
        return view(self::$view_path . 'create', $data);
    }


    /**商品编辑页面
     * @param Request $request
     * @param Props $propsModel
     * @param Goods $goodsModel
     */
    public function edit_form(Request $request, Props $propsModel, Goods $goodsModel,Product $product,$spu_id)
    {
        $data['goods_row'] = Goods::find($spu_id);

        #sku列表
        list($data['sku_list'],$data['property_list'],$data['product_id_arr']) = $product -> get_sku_prop_data($spu_id);
        #可供选择的商品规格列表
        $data['pro_val_list'] = $propsModel->getProplist();

        #分类列表
        $data['cat_list'] = $goodsModel->getHtmlCate(Category::all()->toArray());
        $data['action'] = 'edit';
        return view(self::$view_path . 'edit', $data);
    }

    /**商品编辑方法
     * @param Request $request
     * @param Goods $goodsModel
     * @return mixed
     */
    public function doedit(Request $request,Goods $goodsModel)
    {
//        var_dump($request->input('goods_id'));
//        dd($request->all());
        if (!$goodsModel->edit($request->input('goods_id'),$request->all())) {
            return ApiController::response(null, ApiController::ERROR_CODE, $goodsModel->error);
        }

        return ApiController::response();
    }

    /**商品的删除
     * @param Request $request
     * @param Goods $goodsModel
     * @param int $spu_id  商品的spu_id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function del(Request $request,Goods $goodsModel,$spu_id=0)
    {
        if(empty($spu_id)){
            return redirect('admin/spu/index')->with('success','商品删除成功');
        }
        if($goodsModel -> del($spu_id)){
            return redirect('admin/spu/index')->with('success','商品删除成功');
        }

        redirect('admin/spu/index')->with('danger',$goodsModel->error);
    }

    /**获取编辑图片的列表
     * @return \Illuminate\Http\JsonResponse
     */
    public function bsImgConfig(Request $request,$spu_id=null)
    {
        if(empty($spu_id)){
            $list = [];
        }
        #商品图片列表
        $list = GoodsImage::query()->select('goods_image_id AS image_id','image AS url','is_default')->where('goods_id',$spu_id)->where('disabled','0')->get()->toArray();
        $data = $this -> generateBsConfig($list);

        return response()->json($data);
    }

    /**bootstrapfileinput上传方法
     * @param Request $request  request类
     * @param ImageUploadHandler $uploader 上传类
     * @return mixed
     */
    public function uploadImg(Request $request,ImageUploadHandler $uploader)
    {
        if(!$request -> image){
            return self::bsresponse(['error'=>'未上传文件']);
        }

        if(!$path = $uploader -> save($request -> image,'spu',1,false)){
            return self::bsresponse(['error'=>'图片上传出错,请重试']);
        }

        return self::bsresponse(['error'=>'','db_url'=>$path['path'],'web_url'=>$path['path']]);
    }

    /**删除上传的图片
     * @param Request $request
     */
    public function deleteImg(Request $request)
    {
        if(!empty($request->input('key'))){
            //说明是存储在数据库中的图片
            GoodsImage::find($request->input('key'))->delete();
        }
        //以下是在文件中删除图片
        $file_path = public_path().$request->input('db_path');
        if(file_exists($file_path)){
            unlink($file_path);
        }

        return response()->json(['error'=>'']);
    }

    /**商品的批量上架或者下架
     * @param Request $request
     * @param $spu_id
     * @param $marketable
     */
    public function market(Request $request,Goods $goodsModel,$spu_id,$marketable)
    {
        $msg = $marketable == 0? '下架' :'上架';
        if($goodsModel->market(explode(',',$spu_id),$marketable)>0){
            return redirect()->back()->with('success','批量'.$msg.'成功');
        }
        return redirect()->back()->with('danger','批量'.$msg.'失败，请稍后再试');
    }

    /**返回适用于bootstrapfileinput插件的响应
     * @param $data
     * @return \Illuminate\Http\JsonResponse
     */
    public static function bsresponse($data)
    {
        if(!empty($data['error'])){
            $data = ['db_url'=>'','web_url'=>''];
        }
        $hidden_input = <<<STRING
<input type="hidden" value="0" name="Image[default][]">
<input type="hidden" value="0" name="Image[key][]">
<input type="hidden" value="{$data['db_url']}" name="Image[url][]">
STRING;
        $msg = [
            'error' => $data['error'],
            'initialPreview'=>[
                $data['web_url'],
            ],
            'initialPreviewConfig'=>[
                ['previewAsData'=>true,'extra'=>['db_path'=>$data['db_url'],'_token'=>csrf_token()],'key'=>0]
            ],
            'initialPreviewThumbTags'=>[
                [
                    '{default}'     => '<span class="btn btn-default btn-sm btn-set-main-iamge">设为主图</span>',
                    '{hidden_input}'=> $hidden_input
                ]
             ],
//            'append'=>true
        ];
        return response()->json($msg);
    }

    /**根据图片列表数组生成用于bootstrap前端显示的方法
     * @param $imageList 图片列表
     * @return array
     */
    protected function generateBsConfig($imageList)
    {
        $bootstrapConfig = [
            'initialPreview' => [],
            'initialPreviewConfig'=>[],
            'initialPreviewThumbTags'=>[],
        ];
        foreach($imageList as $image)
        {
            $mian_class = ' btn-default btn-set-main-iamge';
            $text = '设为主图';
            $hidden_input = <<<STRING
<input type="hidden" value="0" name="Image[default][]">
<input type="hidden" value="{$image['image_id']}" name="Image[key][]">
<input type="hidden" value="{$image['url']}" name="Image[url][]">
STRING;

            if($image['is_default']){
                $mian_class = ' btn-success bs-main';
                $text = '主图';
                $hidden_input = <<<STRING
<input type="hidden" value="1" name="Image[default][]">
<input type="hidden" value="{$image['image_id']}" name="Image[key][]">
<input type="hidden" value="{$image['url']}" name="Image[url][]">
STRING;
            }
            $bootstrapConfig['initialPreview'][] = $image['url'];
            $bootstrapConfig['initialPreviewConfig'][] = [
                'previewAsData' => true,
                'extra' => [
                    'db_path'=> $image['url'],
                    '_token' => csrf_token()
                ],
                'key' => $image['image_id'],
            ];
            $bootstrapConfig['initialPreviewThumbTags'][] = [
                '{default}'     => '<span class="btn btn-sm '.$mian_class.'">'.$text.'</span>',
                '{hidden_input}'=> $hidden_input
            ];
        }

        return $bootstrapConfig;
    }



}
